(function(){
	angular.module('app')
	.factory('myUtils', ['$rootScope', '$timeout', '$document','$uibModal','$filter', function( $rootScope,$timeout,$document,$uibModal,$filter){
		return {
			createImgsrc : function( data, options ){
				var data = data || {},
					src = '';
				op_str = options ? [options.width, 'x', options.height, '/'].join('') : '';
				if( data.pic_name ){
					src = [data.host, data.dir, op_str, data.material_path, data.pic_name].join('');
				}else{
					src = [data.host, data.dir, op_str, data.filepath, data.filename].join('');
				}
				return src;
			},
			createTime : function( time ){
				var newTime;
				 if( !time ){
				 	newTime = Date.parse(new Date());
				 }else{
				 	newTime  = time /1000;
				 }
				 return newTime
			},
			confirm : function( options, cbk ){
				if( !options.msg ){
					return false;
				}
				var template='<div class="modal-sm tip_modal">'+
					'<div class="modal-content">'+
						'<div class="modal-header">'+
							'<h5 class="modal-title">提醒</h5>'+
						'</div>'+
						'<div class="modal-body text-center p-lg">'+
							'<p>'+
								'<span class="icon-tixing"></span>'+
								'<span>{{msg}}</span>'+
							'</p>'+
						'</div>'+
						'<div class="modal-footer">'+
							'<button type="button" class="btn btn-sure p-x-md" ng-click="save()">确定</button>'+
							'<button type="button" class="btn cancel-btn p-x-md" ng-click="close()" >取消</button>'+
						'</div>'+
					'</div>'+
				'</div>';

				var openModal = $uibModal.open({
					template:  template,
					windowClass: options.winclass || 'conformModal',
					index: 10,
					controller : ['$scope','$uibModalInstance', function( $scope,$uibModalInstance ){
						$scope.msg=options.msg;
						$scope.close = function(){
							$uibModalInstance.dismiss('cancel');
						};
						$scope.save= function () {
							$uibModalInstance.dismiss('cancel');
							$.isFunction(cbk) && cbk(true);
						}
					}]
				});
			},
			
			pad : function(string, len){
		        len = len || 2;
		        string += '';
		        return len - string.length ? len - string.length + 1 > 0 && (new Array(len - string.length + 1)).join("0") + string || string : string;
		  	},
			
			counter : function( range, str ){
				range = Math.floor( range/1000 );
				var day = Math.floor( range / (24 * 60 * 60) ),
					hour = this.pad(Math.floor( range % (24 * 60 * 60) /(60 * 60))),
					min = this.pad(Math.floor( range % (24 * 60 * 60) %(60 * 60) / 60)),
					sec = this.pad(Math.floor( range % (24 * 60 * 60) %(60 * 60) % 60));
				if( str ){
					if( str.match( 'day' ) ){
						str = str.replace('day', day).replace('hour', hour);
					}else{
						str = str.replace( 'hour', this.pad(parseInt( hour ) + parseInt( day ) * 24 ));
					}
					str = str.replace('min', min)
						.replace('sec', sec);
				}else{
					str = day + '天' + hour + '小时'; 
				}
				return str;
			},
			
			cookie : function(name, value, options) {
			    if (typeof value != 'undefined') {
			        options = options || {};
			        if (value === null) {
			            value = '';
			            options.expires = -1;
			        }
			        var expires = '';
			        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
			            var date;
			            if (typeof options.expires == 'number') {
			                date = new Date();
			                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			            } else {
			                date = options.expires;
			            }
			            expires = '; expires=' + date.toUTCString();
			        }
			        var path = options.path ? '; path=' + options.path : '';
			        var domain = options.domain ? '; domain=' + options.domain : '';
			        var secure = options.secure ? '; secure' : '';
			        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
			    } else {
			        var cookieValue = null;
			        if (document.cookie && document.cookie != '') {
			            var cookies = document.cookie.split(';');
			            for (var i = 0; i < cookies.length; i++) {
			                var cookie = $.trim(cookies[i]);
			                if (cookie.substring(0, name.length + 1) == (name + '=')) {
			                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
			                    break;
			                }
			            }
			        }
			        return cookieValue;
			    }
			},
				/*
			 * 分开的时间格式
			 * */
			separateTime : function( stamp ){
				stamp = stamp || +new Date();
				var dateFilter = $filter('date');
				if( stamp.toString().length == 10 ){
					stamp = stamp.toString() + '000';
				}
				stamp = +stamp;
				return {
					year : dateFilter( stamp, 'yyyy' ),
					month : dateFilter( stamp, 'MM' ),
					day : dateFilter( stamp, 'dd' ),
					hour : dateFilter( stamp, 'HH' ),
					minute : dateFilter( stamp, 'mm' ),
					second : dateFilter( stamp, 'ss' ),
					week : dateFilter( stamp, 'EEEE' )
				}
			},
		
			
			isValidNum : function( num ){
				return /^[1-9]\d*$/.test( num );
			},

			isUrl : function( value ){
				return /^((http|https):\/\/(\w+:{0,1}\w*@)?(\S+)|)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/.test(value);
			},
			
			tip : function( options, cbk ){
				if( !options.msg ){
					return false;
				}
		        var openModal = $uibModal.open({
		            template: '<uib-alert type="' + ( options.type || 'danger' ) + '" close="close()">' + options.msg + '</uib-alert>',
		            windowClass: options.winclass || 'tipModal',
		            index: 10,
		            controller : ['$scope','$uibModalInstance', function( $scope,$uibModalInstance ){
		            	$scope.close = function(){
		            		$uibModalInstance.dismiss('cancel');
		            		$.isFunction(cbk) && cbk();
		            	};
		            }],
		            backdrop: false,
		          });
		        $timeout(function () {
		          openModal.close();
		          $.isFunction(cbk) && cbk();
		        }, options.delay || 2000);
			},
			
			vertifySpecial : function( val ){
				var reg1 = /[~#^$@%&*]/gi,
					reg2 = /^\s+$/;
				if( val.match( reg1 ) ){
					return '不能包含特殊字符';
				}
				if( val.match( reg2 ) ){
					return '不能全为空格';
				}
				return false;
			},
			storage : {
				method : 'localStorage',
				set : function( key, value, time, method ){
					method = method || this.method;
					var data = {
						value : JSON.stringify( value )
					};
					if( typeof time == 'number' ){
						var valid = time * 60 * 1e3;
						data.timestamp = ( new Date ).getTime() + valid
					}else{
						data.timestamp = null;
					}
					return window[method].setItem( key, JSON.stringify( data ) );
				},
				get : function( key, method ){
					method = method || this.method;
					var data = JSON.parse( window[method].getItem( key ) );
					return data && data.value ? data.timestamp === null ? JSON.parse( data.value ) : ( new Date ).getTime() < data.timestamp && JSON.parse( data.value ) || !1 : !1;
				},
				remove : function( key, method ){
					method = method || this.method;
					window[method].removeItem( key );
				},
				clear : function( method ){
					method = method || this.method;
					window[method].clear();
				}
		  	},

		}
	}])

	.filter("toHtml", ["$sce", function( $sce ) {
		return function( input ) {
			return $sce.trustAsHtml( input );
		}
	}]);
})();
